package com.myweb.demo.controller;

import com.myweb.demo.entity.Admin;
import com.myweb.demo.entity.Posts;
import com.myweb.demo.entity.User;
import com.myweb.demo.repository.AdminRepository;
import com.myweb.demo.repository.PostsRepository;
import com.myweb.demo.repository.UserRepository;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    AdminRepository adminRepository;
    @Autowired
    UserRepository userRepository;

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public ModelAndView getAdmin(Model model){
        if (!model.containsAttribute("error")){
            model.addAttribute("error","");
        }
        return new ModelAndView("login","userModel",model);
    }

    @RequestMapping(value="/login",method = RequestMethod.POST)
    public ModelAndView loginSuccess(HttpServletRequest request,@RequestParam(value = "username")String username, @RequestParam(value = "password")String password, Model model){
        User user = userRepository.getUserByUserNameAndUserPassword(username,password);
        if (user!=null){
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            return new ModelAndView("redirect:/index","userModel",model);
        }else {
            model.addAttribute("error","用户名或密码错误！");
            return new ModelAndView("login","userModel",model);
        }

    }

}
